//
//  LoginController.swift
//  PhotoLine
//
//  Created by 吴帅 on 17/9/14.
//  Copyright © 2017年 PhotoLine. All rights reserved.
//

import UIKit
import SnapKit
import Alamofire

struct AccountInfo {
    var account : String;
    var password : String;
    init() {
        account = "";
        password = "";
    }
}

class LoginController: RefreshViewController, UITextFieldDelegate {
    
    static let ACCOUNTTEXTFIELDTAG = 10001;
    static let PASSWORDTEXTFIELDTAG = 10002;
    private var accountInfo : AccountInfo = AccountInfo();
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = ThemeColor;
        
        self.setUpSubView();

    }
	
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }
    
    func setUpSubView() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: #imageLiteral(resourceName: "navigation_back"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(LoginController.back))
        
        self.tableView.frame = CGRect.init(x: 20, y: SCREEN_HEIGHT, width: SCREEN_WIDTH-40, height: 300);
        self.tableView.layer.cornerRadius = CORNERRADIUS;
        self.tableView.rowHeight = LoginCell.cellHeight;
        self.tableView.backgroundColor = UIColor.white;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        self.tableView.isScrollEnabled = false;
        self.tableView.tableHeaderView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH-40, height: 20));
        self.tableView.tableFooterView = LoginFootView.init(frame:CGRect.init(x: 0, y: 0, width: SCREEN_WIDTH-40, height: 100));
        
        let footView: LoginFootView = self.tableView.tableFooterView as! LoginFootView;
        footView.loginButton?.addTarget(self, action: #selector(LoginController.login), for: UIControlEvents.touchUpInside);
    }
    
    // MARK: - tableViewDataSource
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2;
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LoginCell = LoginCell.cellWithTableView(tableView: tableView, identifier: "LoginButton") as! LoginCell;
        cell.setPlaceholder(placeholder: "username");
        cell.textField.tag = LoginController.ACCOUNTTEXTFIELDTAG + indexPath.row;
        cell.textField.delegate = self;
        return cell;
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true);
    }
    
    // MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let idx1 = string.characters.index(after: string.startIndex)
        let idxRange = idx1..<string.characters.index(idx1, offsetBy: range.length)
        let text = textField.text?.replacingCharacters(in: idxRange, with: string);
        if textField.tag == LoginController.ACCOUNTTEXTFIELDTAG {
            accountInfo.account = text!;
        } else {
            accountInfo.password = text!;
        }
        return true;
    }
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("aaaaa");
        return true;
    }
    
    // MARK: - public
    public func setupTableViewFrame(animate:Bool) {
        if animate {
            UIView.animate(withDuration: 0.5, animations: {
                self.tableView.frame.origin.y = 150;
            });
        } else {
            self.tableView.frame.origin.y = 150;
        }
    }
    
    // MARK: -private
    func back() {
        UIView.animate(withDuration: 0.5, animations: {
            self.tableView.frame.origin.y = SCREEN_HEIGHT;
        }) { (b) in
            self.navigationController?.dismiss(animated: false, completion: nil);
        };
    }
    
    func login() {
        let footView: LoginFootView = self.tableView.tableFooterView as! LoginFootView;
        let params = ["username":"wushuai",
                      "password":"123456"];
        Alamofire.request("http://39.106.104.91:8080/maven-springmvc/account/login", method: HTTPMethod.get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let json : NSDictionary = response.result.value as? NSDictionary {
                if (json["status"] as! Int == 200) {
                    let navi = NavigationController.init(rootViewController: MainViewController())
                    UIApplication.shared.keyWindow?.rootViewController = navi;
                    footView.loginButton?.endLoading();
                }
            }
        };
    }

}
